package com.itheima.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 小帅蓝
 * @Date 2022/6/22 14:08
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public List<ShoppingCart> queryAll() {
        String userId = TokenHolder.getCurrentId();
        return shoppingCartMapper.queryAll(userId);
    }

    @Override
    public ShoppingCart queryById(String id) {
        return shoppingCartMapper.queryById(id);
    }

    @Override
    public ShoppingCart addShoppingCart(ShoppingCart shoppingCart) {
        //先判断购物车中有没有同名菜品或套餐，有的话取出id作为当前要插入数据的id，执行更新语句
        // 没有生成一个新的id，执行插入语句
        String name = shoppingCart.getName();
        String dishFlavor = shoppingCart.getDishFlavor();

        String userId = TokenHolder.getCurrentId();
        List<ShoppingCart> list = shoppingCartMapper.queryAll(userId);
        List<ShoppingCart> collect = list.stream().filter(s -> s.getName().equals(name)).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(collect)) {
            //有同名同属性菜品
            ShoppingCart co1 = collect.get(0);
            shoppingCart.setId(co1.getId());
        } else {
            shoppingCart.setId(new Snowflake().nextIdStr());
        }
        shoppingCart.setUserId(userId);
        shoppingCartMapper.addShoppingCart(shoppingCart);

        return shoppingCartMapper.queryById(shoppingCart.getId());
    }

    @Override
    public R<String> deleteAll() {
        int row = shoppingCartMapper.deleteAll(TokenHolder.getCurrentId());
        if (row > 0) {
            return R.success("清空购物车成功");
        }
        return R.error("清空购物车失败");
    }

    @Override
    public R<String> deleteShoppingCart(String dishId, String setmealId) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(TokenHolder.getCurrentId());
        shoppingCart.setDishId(dishId);
        shoppingCart.setSetmealId(setmealId);
        //判断当前商品在购物车中的数量
        int number = shoppingCartMapper.queryNumber(shoppingCart);
        if (number == 1) {
            int row = shoppingCartMapper.deleteShoppingCart(shoppingCart);
            return row > 0 ? R.success("删除购物车商品成功") : R.error("删除购物车商品失败");
        }
        int rowUp = shoppingCartMapper.updateNumber(shoppingCart);
        return rowUp > 0 ? R.success("删除购物车商品成功") : R.error("删除购物车商品失败");
    }
}
